package typejump.commands;

import typejump.Messenger;
import typejump.TypeJump;
import typejump.engine.GameEngine;
import typejump.engine.OnGoingThing;
import typejump.objects.GameObject;

public class DevGrab implements TextCommand, OnGoingThing {

	private GameObject obj;
	private double dx, dy, vx, vy;
	
	@Override
	public boolean matches(String command) {
		return command.matches("dev grab(\\s+.*)?");
	}

	@Override
	public void act(String command) {		
		TypeJump tj = TypeJump.getInst();
		
		command = command.substring("dev grab".length()).trim();
		
		int flags = 0;
		if (command.contains("all") || command.contains("back")) flags |= GameEngine.OBJECT_BACK;
		if (command.contains("all") || command.contains("fore")) flags |= GameEngine.OBJECT_FORE;
		if (command.contains("all") || command.contains("main") || flags == 0) flags |= GameEngine.OBJECT_MAIN;
		
		obj = GameEngine.getObjectAt(tj.getMouseX(), tj.getMouseY(), flags);
		
		grab(obj);
		
		GameEngine.addTextEffect("GRAB " + command.toUpperCase(), "dev");
	}
	
	public void pass(Object obj) {
		if (obj == null || !(obj instanceof GameObject)) return;
		GameObject go = (GameObject)obj;
		grab(go);
	}
	
	private void grab(GameObject obj) {
		if (obj == null)
			return;
		
		this.obj = obj;
		
		TypeJump tj = TypeJump.getInst();
		
		if (obj == tj.getPlayer()) {
			GameEngine.setFocusOnPlayer(false);
		}
		
		dx = tj.getMouseX() - obj.centerX();
		dy = tj.getMouseY() - obj.centerY();
		vx = obj.vx();
		vy = obj.vy();

		GameEngine.select(obj);
		GameEngine.addOnGoingThing(this);
	}

	@Override
	public boolean happen(TypeJump tj, double seconds) {
		obj.left(tj.getSnappy(tj.getMouseX() - dx - obj.width()/2));
		obj.top(tj.getSnappy(tj.getMouseY() - dy - obj.height()/2));
		obj.vx(this.vx);
		obj.vy(this.vy);
		if (Messenger.hasMessage("mouse click")) {
			GameEngine.deselect(obj);
			return true;
		}
		return false;
	}

}
